package com.example.guesswho.ui.components

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import com.example.guesswho.util.AudioPlayer
import com.example.guesswho.util.CartoonFilter
import com.example.guesswho.util.UtilityManager
import kotlinx.coroutines.launch

@Composable
fun UtilityDemoCard(
    utilityManager: UtilityManager,
    modifier: Modifier = Modifier
) {
    val context = LocalContext.current
    val scope = rememberCoroutineScope()
    
    var isProcessing by remember { mutableStateOf(false) }
    var filteredBitmap by remember { mutableStateOf<Bitmap?>(null) }
    var uploadedUrl by remember { mutableStateOf<String?>(null) }
    var showImagePicker by remember { mutableStateOf(false) }
    
    // State collection
    val isProcessingImage by utilityManager.isProcessingImage.collectAsState()
    val currentFilterStyle by utilityManager.currentFilterStyle.collectAsState()
    
    // Image picker launcher
    val imagePicker = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.GetContent()
    ) { uri: Uri? ->
        uri?.let {
            scope.launch {
                utilityManager.applyCartoonFilter(it) { result ->
                    result.onSuccess { bitmap ->
                        filteredBitmap = bitmap
                    }
                }
            }
        }
    }
    
    Card(
        modifier = modifier.fillMaxWidth(),
        colors = CardDefaults.cardColors(
            containerColor = MaterialTheme.colorScheme.surfaceVariant
        )
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(16.dp)
        ) {
            Text(
                text = "🎵 音效 + 🎨 卡通滤镜",
                fontSize = 20.sp,
                fontWeight = FontWeight.Bold,
                color = MaterialTheme.colorScheme.onSurfaceVariant
            )
            
            // Audio Demo Section
            Card(
                colors = CardDefaults.cardColors(
                    containerColor = MaterialTheme.colorScheme.surface
                )
            ) {
                Column(
                    modifier = Modifier.padding(12.dp),
                    verticalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    Text(
                        text = "音效测试",
                        fontSize = 16.sp,
                        fontWeight = FontWeight.Medium,
                        color = MaterialTheme.colorScheme.onSurface
                    )
                    
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.spacedBy(8.dp)
                    ) {
                        Button(
                            onClick = { utilityManager.playSuccessSound() },
                            modifier = Modifier.weight(1f)
                        ) {
                            Text("✅ 成功")
                        }
                        Button(
                            onClick = { utilityManager.playFailureSound() },
                            modifier = Modifier.weight(1f)
                        ) {
                            Text("❌ 失败")
                        }
                        Button(
                            onClick = { utilityManager.playRandomEasterEgg() },
                            modifier = Modifier.weight(1f)
                        ) {
                            Text("🥚 彩蛋")
                        }
                    }
                }
            }
            
            // Cartoon Filter Demo Section
            Card(
                colors = CardDefaults.cardColors(
                    containerColor = MaterialTheme.colorScheme.surface
                )
            ) {
                Column(
                    modifier = Modifier.padding(12.dp),
                    verticalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    Text(
                        text = "卡通滤镜测试",
                        fontSize = 16.sp,
                        fontWeight = FontWeight.Medium,
                        color = MaterialTheme.colorScheme.onSurface
                    )
                    
                    // Filter Style Selection
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.spacedBy(4.dp)
                    ) {
                        utilityManager.getAvailableFilterStyles().forEach { styleInfo ->
                            FilterStyleButton(
                                styleInfo = styleInfo,
                                isSelected = currentFilterStyle == styleInfo.style,
                                onClick = { utilityManager.setFilterStyle(styleInfo.style) },
                                modifier = Modifier.weight(1f)
                            )
                        }
                    }
                    
                    // Image Actions
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.spacedBy(8.dp)
                    ) {
                        Button(
                            onClick = { 
                                val defaultBitmap = createDefaultBitmap(context)
                                scope.launch {
                                    utilityManager.applyCartoonFilter(defaultBitmap) { result ->
                                        result.onSuccess { bitmap ->
                                            filteredBitmap = bitmap
                                        }
                                    }
                                }
                            },
                            modifier = Modifier.weight(1f)
                        ) {
                            Text("🖼️ 示例图片")
                        }
                        
                        Button(
                            onClick = { imagePicker.launch("image/*") },
                            modifier = Modifier.weight(1f)
                        ) {
                            Text("📷 选择图片")
                        }
                    }
                    
                    // Upload Button
                    if (filteredBitmap != null) {
                        Button(
                            onClick = {
                                scope.launch {
                                    utilityManager.applyAndUploadCartoonFilter(filteredBitmap!!) { result ->
                                        result.onSuccess { url ->
                                            uploadedUrl = url
                                        }
                                    }
                                }
                            },
                            modifier = Modifier.fillMaxWidth(),
                            enabled = !isProcessingImage
                        ) {
                            if (isProcessingImage) {
                                CircularProgressIndicator(
                                    modifier = Modifier.size(16.dp),
                                    strokeWidth = 2.dp
                                )
                                Spacer(modifier = Modifier.width(8.dp))
                                Text("上传中...")
                            } else {
                                Text("📤 上传到服务器")
                            }
                        }
                    }
                }
            }
            
            // Result Display
            if (uploadedUrl != null) {
                Card(
                    colors = CardDefaults.cardColors(
                        containerColor = MaterialTheme.colorScheme.primaryContainer
                    )
                ) {
                    Column(
                        modifier = Modifier.padding(12.dp),
                        horizontalAlignment = Alignment.CenterHorizontally
                    ) {
                        Icon(
                            imageVector = androidx.compose.material.icons.Icons.Default.CheckCircle,
                            contentDescription = "Success",
                            tint = MaterialTheme.colorScheme.primary,
                            modifier = Modifier.size(32.dp)
                        )
                        Spacer(modifier = Modifier.height(8.dp))
                        Text(
                            text = "上传成功！",
                            fontSize = 16.sp,
                            fontWeight = FontWeight.Medium,
                            color = MaterialTheme.colorScheme.onPrimaryContainer
                        )
                        Text(
                            text = uploadedUrl?.take(50) + "...",
                            fontSize = 12.sp,
                            color = MaterialTheme.colorScheme.onPrimaryContainer.copy(alpha = 0.8f)
                        )
                    }
                }
            }
            
            // Processing Indicator
            if (isProcessingImage) {
                LinearProgressIndicator(
                    modifier = Modifier.fillMaxWidth(),
                    color = MaterialTheme.colorScheme.primary
                )
                Text(
                    text = "正在处理图片...",
                    fontSize = 14.sp,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                    modifier = Modifier.align(Alignment.CenterHorizontally)
                )
            }
        }
    }
}

@Composable
fun FilterStyleButton(
    styleInfo: CartoonFilter.FilterStyleInfo,
    isSelected: Boolean,
    onClick: () -> Unit,
    modifier: Modifier = Modifier
) {
    OutlinedButton(
        onClick = onClick,
        modifier = modifier.height(40.dp),
        colors = ButtonDefaults.outlinedButtonColors(
            containerColor = if (isSelected) MaterialTheme.colorScheme.primaryContainer else Color.Transparent,
            contentColor = if (isSelected) MaterialTheme.colorScheme.onPrimaryContainer else MaterialTheme.colorScheme.primary
        )
    ) {
        Text(
            text = styleInfo.displayName,
            fontSize = 12.sp,
            maxLines = 1
        )
    }
}

private fun createDefaultBitmap(context: android.content.Context): Bitmap {
    // Create a simple test bitmap
    val size = 200
    val bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888)
    val canvas = android.graphics.Canvas(bitmap)
    val paint = android.graphics.Paint()
    
    // Draw a colorful gradient
    val gradient = android.graphics.LinearGradient(
        0f, 0f, size.toFloat(), size.toFloat(),
        intArrayOf(
            android.graphics.Color.RED,
            android.graphics.Color.GREEN,
            android.graphics.Color.BLUE
        ),
        null,
        android.graphics.Shader.TileMode.CLAMP
    )
    paint.shader = gradient
    canvas.drawRect(0f, 0f, size.toFloat(), size.toFloat(), paint)
    
    return bitmap
}